import os

from apps.courses.models import Courses, Lesson, Video, CourseResourse, BannerCourse, CourseDiscuss

import xadmin
from apps.operation.models import UserMessage, UserCourse
from apps.utils.image_storage import image_upload, video_upload
from djangoProject.settings import TEMP_VIDEO_PATH, QINIU_DOMIN_PREFIX, VIDEO_PATH
from xadmin.layout import Main, Fieldset, Row, Side


class CoursesAdmin(object):
    list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'click_nums']
    search_fields = ['name', 'desc', 'detail', 'degree', 'students']
    list_filter = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
    list_editable = ['degree', 'desc']
    ordering = ['-click_nums']
    model_icon = 'fa fa-file-video-o'


class LessonAdmin(object):
    list_display = ['course', 'name', 'add_time']
    search_fields = ['course', 'name']
    list_filter = ['course__name', 'name', 'add_time']
    model_icon = 'fa fa-film'


'''添加教师上传视频功能--视频存储到七牛云  2022-1.11 0:15  绷不住了家人们'''


class VideoAdmin(object):
    list_display = ['lesson', 'name', 'url', 'video_file', 'add_time']
    search_fields = ['lesson', 'name', 'add_time', 'video_file']
    list_filter = ['lesson', 'name', 'add_time', 'video_file']
    model_icon = 'fa fa-video-camera'
    readonly_fields = ['url']

    def save_models(self):
        obj = self.new_obj
        if not obj.id:
            filename = obj.video_file.name
            # print(obj.video_file.file_path)
            file_path = VIDEO_PATH + obj.video_file.name
            obj.save()
            video_path = video_upload(TEMP_VIDEO_PATH + filename, file_path)
            obj.url = QINIU_DOMIN_PREFIX + video_path
            obj.save()
            print(obj.url)
            if os.path.exists(TEMP_VIDEO_PATH + filename):
                os.remove(TEMP_VIDEO_PATH + filename)
            user_course_list = UserCourse.objects.filter(course=obj.lesson.course).all()
            print(user_course_list)
            for user_course in user_course_list:
                usermessage = UserMessage()
                usermessage.user = user_course.user
                usermessage.message = "您的课程:【<a href='/course/lesson/{0}/'>{1}</a>】 发布了新的视频:【<a href='/course/{2}/video/{3}'>{4}</a>】 ".format(
                    obj.lesson.course.id, obj.lesson.course, obj.lesson.course.id, obj.id, obj.name)
                usermessage.save()
        else:
            try:
                filename = obj.video_file.name
                file_path = VIDEO_PATH + obj.video_file.name
                obj.save()
                video_path = video_upload(TEMP_VIDEO_PATH + filename, file_path)
                obj.url = QINIU_DOMIN_PREFIX + video_path
                obj.save()
                if os.path.exists(TEMP_VIDEO_PATH + filename):
                    os.remove(TEMP_VIDEO_PATH + filename)
            except Exception as e:
                print(e)


class CourseResourceAdmin(object):
    list_display = ['course', 'name', 'download', 'add_time']
    search_fields = ['course', 'name', 'download']
    list_filter = ['course', 'name', 'download', 'add_time']
    model_icon = 'fa fa-download'

    def save_models(self):
        obj = self.new_obj
        print(obj)
        if not obj.id:
            obj.save()
            user_course_list = UserCourse.objects.filter(course=obj.course).all()
            for user_course in user_course_list:
                usermessage = UserMessage()
                usermessage.user = user_course.user
                usermessage.message = "您的课程:【<a href='/course/lesson/{0}/'>{1}</a>】 上传了新的资料:【<a href='{2}'>{3}</a>】 ".format(
                    obj.course.id, obj.course, obj.download.url, obj.name)
                usermessage.save()

        obj.save()


class CourseDiscussAdmin(object):
    list_display = ['course', 'title', 'discuss_content', 'read_nums', 'add_time']
    search_fields = ['course', 'title', 'discuss_content', 'read_nums', 'add_time']
    list_filter = ['course', 'title', 'discuss_content', 'read_nums']
    model_icon = 'fa fa-th'

    # def queryset(self):
    #     qs = super().queryset()
    #     print(self.request.user.teacher.teacher_course())
    #     if not self.request.user.is_superuser:
    #         # teacher=
    #         qs = qs.filter(course = self.request.user.teacher.teacher_course)
    #     return qs

    def save_models(self):
        course_obj = self.new_obj
        print(course_obj)
        if not course_obj.id:
            course_obj.save()
            user_course_list = UserCourse.objects.filter(course=course_obj.course).all()
            for user_course in user_course_list:
                usermessage = UserMessage()
                usermessage.user = user_course.user
                usermessage.message = "您的课程:【<a href='/course/lesson/{0}/'>{1}</a>】 发布了新的讨论:【<a href='/course/{2}/discuss/{3}'>{4}</a>】 ".format(
                    course_obj.course.id, course_obj.course,
                    course_obj.course.id, course_obj.id, course_obj.title,
                    )
                usermessage.save()

        course_obj.save()

    # def queryset(self):
    #         qs = super().queryset()
    #         if not self.request.user.is_superuser:
    #             qs = qs.filter(course.teacher=self.request.user.teacher)
    #         return qs


# 课程轮播图
class BannerCourseAdmin(object):
    list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
    search_fields = ['name', 'desc', 'detail', 'degree', 'students']
    list_filter = ['name', 'teacher__name', 'desc', 'detail', 'degree', 'learn_times', 'students']
    list_editable = ["degree", "desc"]
    model_icon = 'fa fa-file-image-o'

    def queryset(self):
        qs = super().queryset()
        qs = qs.filter(is_banner=True)
        return qs


'''自定义布局'''


# 一个页面编辑多张表需要有外键支持
class LessonInline(object):
    model = Lesson
    # style = "tab"
    # 自动添加一个空白标签 0不添加 1 添加
    extra = 1
    exclude = ["add_time"]


class CourseResourceInline(object):
    model = CourseResourse
    # style = "tab"
    extra = 1
    exclude = ["add_time"]


# 数据导出
from import_export import resources


class MyResource(resources.ModelResource):
    class Meta:
        model = Courses
        # fields = ('name', 'description',)
        # exclude = ()


class NewCourseAdmin(object):
    import_export_args = {'import_resource_class': MyResource, 'export_resource_class': MyResource}
    list_display = ['name', 'show_image', 'go_to', 'desc', 'category', 'degree', 'learn_times', 'students',
                    'click_nums']
    search_fields = ['name', 'desc', 'detail', 'degree', 'students']
    list_filter = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
    list_editable = ['degree', 'desc']
    ordering = ['-click_nums']
    model_icon = 'fa fa-file-video-o'
    # 只读字段
    readonly_fields = ["students", "add_time", "fav_nums"]
    # 添加时不显示
    # exclude = ["click_nums", "fav_nums"]
    # 一个页面编辑多个表数据
    inlines = [LessonInline, CourseResourceInline]
    # 字段显示成富文本
    style_fields = {
        "detail": "ueditor"
    }

    '''显示自己的课程信息'''

    def queryset(self):
        qs = super().queryset()
        if not self.request.user.is_superuser:
            qs = qs.filter(teacher=self.request.user.teacher)
        return qs

    # def save_models(self):
    #     obj = self.new_obj
    #     print()
    #     print(type(obj.image))
    #     print(obj.image.url)
    #     # print(obj.image.read())
    #     if not obj.id:
    #         obj.save()

    def get_form_layout(self):
        if self.org_obj:
            self.form_layout = (
                Main(
                    Fieldset("讲师信息",
                             'teacher', 'course_org',
                             css_class='unsort no_title'
                             ),
                    Fieldset("基本信息",
                             'name', 'desc',
                             Row('learn_times', 'degree'),
                             Row('category', 'tag'),
                             'youneed_know', 'teacher_tell', 'detail',
                             ),
                ),
                Side(
                    Fieldset("访问信息",
                             'fav_nums', 'click_nums', 'students', 'add_time'
                             ),
                ),
                Side(
                    Fieldset("选择信息",
                             'is_banner', 'is_classics'
                             ),
                )
            )
        return super(NewCourseAdmin, self).get_form_layout()


# xadmin.site.register(Courses, CoursesAdmin)
xadmin.site.register(Courses, NewCourseAdmin)
xadmin.site.register(CourseDiscuss, CourseDiscussAdmin)
xadmin.site.register(BannerCourse, BannerCourseAdmin)
xadmin.site.register(Lesson, LessonAdmin)
xadmin.site.register(Video, VideoAdmin)
xadmin.site.register(CourseResourse, CourseResourceAdmin)
